package yyy.ab.logging.service.impl;

import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import yyy.ab.common.core.Query;
import yyy.ab.common.core.ResultBean;
import yyy.ab.common.utils.StringUtils;
import yyy.ab.logging.entity.SysLog;
import yyy.ab.logging.mapper.SysLogMapper;
import yyy.ab.logging.service.SysLogService;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

@Service
@RequiredArgsConstructor
public class SysLogServiceImpl extends ServiceImpl<SysLogMapper, SysLog> implements SysLogService {

    private final SysLogMapper baseMapper;

    @Override
    public IPage<SysLog> findPage(Map<String, Object> params) {
        Object keyword = params.get("keyword");
        Object logType = params.get("logType");
        QueryWrapper<SysLog> queryWrapper = new QueryWrapper<SysLog>().select("id", "create_time", "description", "method", "params", "request_ip", "time", "username", "address", "browser")
                .eq("log_type", logType)
                .like(!StringUtils.isNullOrEmpty(keyword), "description", keyword)
                .orderByDesc("create_time");
        Page<SysLog> page = new Query<SysLog>(params).getPage();
        return baseMapper.selectPage(page, queryWrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void save(String username, String browser, String ip, ProceedingJoinPoint joinPoint, StringBuilder params, SysLog log) {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        // 方法路径
        String methodName = signature.getDeclaringTypeName() + "." + signature.getName();
        yyy.ab.logging.annotation.Log logAnnotation = method.getAnnotation(yyy.ab.logging.annotation.Log.class);
        // 注解上的描述
        if (log != null && logAnnotation != null) {
            log.setDescription(logAnnotation.value());
        }
        assert log != null;
        log.setRequestIp(ip);
        log.setAddress(StringUtils.getCityInfo(log.getRequestIp()));
        log.setMethod(methodName);
        log.setUsername(username);
        log.setParams(params.toString());
        log.setBrowser(browser);
        super.save(log);
    }
}
